#include"translate.h"
int translate(FILE* f, node_t* n)
{
    assert(f);
    if(n == NULL)
        return 0;
    //some critical cases
    if(n->lex->opType == DEC && n->right->lex->lexType != FUNCTION)
    {
        fprintf(f, "!%s\n", n->right->lex->name);
        if (n->right->left) translate(f, n->right->left);
        return 0;
    }
    if(n->lex->opType == MOV)
    {
        translate(f, n->right);
        fprintf(f, "pop %s\n", n->left->lex->name);
        return 0;
    }
    if(n->lex->lexType == FUNCTION)
    {
        fprintf(f, "func %s\n", n->lex->name);
        translate(f, n->left);
        fprintf(f, "|\n");
        return 0;
    }

    if(n->left) translate(f, n->left);
    if(n->right) translate(f, n->right);
    printAssembled(f, n);
    return 0;
}

int printAssembled(FILE* f, node_t* n)
{
    switch(n->lex->lexType)
    {
        case NUMBER:
            fprintf(f, "push %lg\n", n->lex->value);
            break;
        case VARIABLE:
            fprintf(f, "push %s\n", n->lex->name);
            break;
        case OPERATOR:
            switch(n->lex->opType)
            {
                case ADD:
                    fprintf(f, "add\n");
                    break;
                case MINUS_BIN:
                    fprintf(f, "sub\n");
                    break;
                case MUL:
                    fprintf(f, "mul\n");
                    break;
                case DIV:
                    fprintf(f, "div\n");
                    break;
                case SKIP:
                    fprintf(f, "|\n");
                    break;
                default:
                    return 0;
            }
        default:
            return 0;
    }
    return 0;
}
